import { useEffect, useState, useCallback, useRef } from 'react'
// import { Spin } from 'antd'
import { useNavigate } from 'react-router-dom'
import SvgIcon from '@/components/svg-icon/SvgIcon.tsx'
import { _getAssets } from '@/utils/assets.ts'
import { getRandomPoetry, Poetry } from '@/utils/poems.ts'
import styles from './Article.module.scss'
import microphone from '@/assets/article/microphone.png'
import collectIcon from '@/assets/article/collect.svg'
import moreIcon from '@/assets/article/more.svg'
import timeIcon from '@/assets/article/time.svg'
import likeIcon from '@/assets/article/like.svg'
import commentIcon from '@/assets/article/comment.svg'
import { _getClassificationArticleList } from '@/http/article/article.service.ts'
import { ArticleWithClassificationVO } from '@/http/article/article.types.ts'
import { Response } from '@/http/public.types.ts'

function Article() {
  const [currentPoems, setCurrentPoems] = useState<Poetry | null>(null)
  const [displayText, setDisplayText] = useState('') // 存储逐字显示的文本
  const [isTyping, setIsTyping] = useState(false) // 控制是否正在输入
  const interval = useRef<NodeJS.Timeout | null>(null) // 用来存储 setInterval 的引用
  const indexRef = useRef(0) // 用 useRef 来存储 index，避免每次渲染时被重置
  const articleList = useRef<ArticleWithClassificationVO[]>([])
  const navigate = useNavigate()

  useEffect(() => {
    setCommonBg()
    const poems = getRandomPoetry()
    setCurrentPoems(poems)

    init()

    return () => {
      if (interval.current) {
        clearInterval(interval.current)
      }
    }
  }, [])

  function init() {
    _getClassificationArticleList().then((res) => {
      if (res.code === Response.SUCCESS) {
        articleList.current = res!.data!
      }
    })
  }

  const goToDetail = (id: string) => {
    navigate(`/article-detail/${id}`)
  }

  const setCommonBg = () => {
    const bgList = ['article-bg.jpg']
    const randomIndex = Math.floor(Math.random() * bgList.length)
    document.documentElement.style.setProperty(
      '--common-bg',
      `url(${_getAssets(bgList[randomIndex], 'bg')}` + ')'
    )
  }

  // function getFirstChar(str: string): string {
  //   return str.charAt(0)
  // }

  // 使用 useCallback 来保证 typeText 函数不会在每次渲染时重新定义
  const typeText = useCallback((text: string) => {
    const poems = getRandomPoetry()
    setCurrentPoems(poems)
    indexRef.current = 0 // 重置 index

    // setDisplayText(getFirstChar(text)) // 清空之前的内容
    setDisplayText('') // 清空之前的内容
    setIsTyping(true)

    if (interval.current) {
      clearInterval(interval.current) // 如果之前有定时器，先清除
    }

    interval.current = setInterval(() => {
      setDisplayText((prevText) => {
        if (text[indexRef.current] !== undefined) {
          return prevText + text[indexRef.current]
        }
        return prevText
      })
      indexRef.current++ // 使用 useRef 的 index

      if (indexRef.current === text.length) {
        clearInterval(interval.current as any) // 输入完成，清除定时器
        setIsTyping(false) // 设置为不在输入
        setTimeout(() => {
          setDisplayText('') // 清空文本，准备重新开始
          typeText(text) // 重新开始逐字输入
        }, 5 * 1000) // 停留5秒后重新开始
      }
    }, 200) // 每200ms显示一个字符
  }, []) // useCallback 的依赖项为空数组，表示 typeText 不会改变

  useEffect(() => {
    if (currentPoems?.content) {
      typeText(currentPoems.content)
    }
  }, [currentPoems, typeText]) // 添加 typeText 到依赖项数组

  return (
    <div className={styles.article}>
      <div className={styles.articleMain}>
        <div className={styles.header}>
          <span className={styles.title}>{currentPoems?.title}~</span>
          <div className={styles.poemsContainer}>
            {displayText}
            {isTyping && <span className={styles.cursor}></span>} {/* 仅在正在输入时显示光标 */}
          </div>

          <div className={styles.wave1}></div>
          <div className={styles.wave2}></div>
        </div>
        <div className={styles.body}>
          <div className={styles.aside}>
            <div className={styles.userInfoContainer}>
              <img
                className={styles.avatar}
                src="https://b0.bdstatic.com/866674faedf144086e041bc0a4906d67.jpg@h_1280"
                alt="头像"
              />

              <span className={styles.name}>风萧兮</span>

              <div className={styles.webInfo}>
                <div className={styles.box}>
                  <span className={styles.info}>文章</span>
                  <span className={styles.info}>100</span>
                </div>
                <div className={styles.box}>
                  <span className={styles.info}>分类</span>
                  <span className={styles.info}>2</span>
                </div>
                <div className={styles.box}>
                  <span className={styles.info}>访问量</span>
                  <span className={styles.info}>100000</span>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.main}>
            <div className={styles.musicContainer}>
              <img src={microphone} className={styles.microphone} alt="microphone" />
              <div className={styles.info}>
                <span className={styles.text}>『如跛脚的孤狼穿越过雪原几世纪』</span>
                <span className={styles.text}>可是我爱你，如跛脚的孤狼穿越过雪原几世纪</span>
              </div>
            </div>

            {articleList.current.map((item) => {
              return (
                <div key={item.classificationId} className={styles.collectContainer}>
                  <div className={styles.collectContainerHeader}>
                    <div className={styles.left}>
                      <SvgIcon src={collectIcon} width={'20px'} height={'20px'} />

                      <span className={styles.text}>{item.classificationName}</span>
                    </div>
                    <div className={styles.right}>
                      <SvgIcon src={moreIcon} width={'20px'} height={'20px'} />
                      <span className={styles.text}>MORE</span>
                    </div>
                  </div>

                  <div className={styles.collectContainerBody}>
                    {item.articleList.map((i) => {
                      return (
                        <div
                          key={i.id}
                          className={styles.articleItem}
                          onClick={() => {
                            goToDetail(i.id)
                          }}
                        >
                          <img src={i.pic} className={styles.image} alt="" />
                          <div className={styles.articleInfo}>
                            <div className={styles.time}>
                              <SvgIcon src={timeIcon} width={12} height={12} />
                              发布于 {i.gmtCreate}
                            </div>
                            <p className={styles.title}>{i.articleName}</p>

                            <div className={styles.operateAndCount}>
                              <div className={styles.item}>
                                <SvgIcon src={likeIcon} width={16} height={16} />
                                <span className={styles.count}>11</span>
                              </div>
                              <div className={styles.item}>
                                <SvgIcon src={commentIcon} width={16} height={16} />
                                <span className={styles.count}>12</span>
                              </div>
                            </div>

                            <div className={styles.tag}>
                              <span className={styles.tagItem}># {item.classificationName}</span>
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>
              )
            })}
            {/*<Spin />*/}
          </div>
        </div>
      </div>
    </div>
  )
}

export default Article
